﻿using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using NModbus;

namespace EONFULLSIN.Views.Device
{
    /// <summary>
    /// 聚英通信协议类
    /// </summary>
    public class ModbusJYHelper
    {
        private static string ipAddress = "192.168.1.232";
        private static int port = 10000;
        private static byte slaveId = 1;
        private static ushort startAddress = 0;
        private static ushort numRegisters = 32;
        ushort[] registers;
   

   

        public async Task<ushort[]> getData()
        {
            try
            {
                Trace.WriteLine("jy connect..");
                using (var tcpClient = new TcpClient(ipAddress, port))
                {
                    tcpClient.ReceiveTimeout = 10*1000;
                    tcpClient.SendTimeout = 10*1000;
                    // 创建Modbus工厂
                    var factory = new ModbusFactory();

                    // 创建Modbus主站（Master）
                    var master = factory.CreateMaster(tcpClient);
                    // 读取保持寄存器
                   
                    registers =await master?.ReadInputRegistersAsync(slaveId, startAddress, numRegisters);

                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine($"jy Error: {ex.Message}");
                retry();
            }
            return registers;
        }

        private void retry()
        {
            Trace.WriteLine("jy retry..");
            getData();
        }
    }
}
